import { useEffect, useState, useCallback } from 'react';
import { FormPath } from '@formily/core';
import { createSchemaFormRender } from "@/components/schema-form-render"
import {
    useField,
  } from '@formily/react';
/**
 * 高阶新增页面，事件注册
 * @param target context
 * @param events 注册事件对象
 * @param params 注册事件执行参数
 */
export const registerEvent = (target: any, events: any, params: any) => {
    if (events) {
        Object.keys(events).forEach(hookName => {
            target[hookName] = () => {
                events[hookName](params)
            }
        })
    }
}

/**
 * 高阶列表页面，列表按钮事件注册
 * @param target context
 * @param events 注册事件对象
 * @param params 注册事件执行参数
 */
export const registerListTableEvent = (target: any, events: any, params: any) => {
    Object.keys(events).forEach(hookName => {
        let old:any = null
        if (target[hookName]) {
           old = target[hookName];
        }
        target[hookName] = async (id: string, row: any, index: number) => {
            if (events && events[hookName]) {
                const res: any = await events[hookName](id, row, params, index);
                if (res?.success) {
                    row.callback && row.callback();
                }
                old && old();
            }
        }
    })
}

/**
 * 高阶列表页面，普通按钮注册
 * @param target context
 * @param events 注册事件对象
 * @param params 注册事件执行参数
 */
export const registerListButtonEvent = (target: any, events: any, params: any) => {
    Object.keys(events).forEach(hookName => {
        let old:any = null
        if (target[hookName]) {
           old = target[hookName];
        }
        target[hookName] = async () => {
            if (events && events[hookName]) {
                const res: any = await events[hookName](params);
                if (res?.success) {
                }
                old && old();
            }
        }
    })
}

/**
 * 
 * @param filedConfig 字段配置
 * @param formConfigs form 配置
 * @param initForm 初始化 form 方法
 * @returns 
 */
export const useScemaRender = (filedConfig: any, formConfigs: any, initForm?: any) => {
    const [configs, setCongis] = useState<any>({
        form: null,
        Render: null,
    })
    useEffect(() => {
        const res = createSchemaFormRender(
            filedConfig,
            formConfigs,
        );
        setCongis(res);
        if (initForm) {
            initForm().then((res2: any) => {
                res.form.setInitialValues(res2.result)
            })
        }
    }, [])
    return {
        form: configs.form,
        SchemaFormRender: configs.Render,
    }
}

/* 
* @returns 返回当前Field绝对路径
*/
export const useGetValue =()=>{
       const field = useField();
       try{
           if(field){
               return field?.address?.entire;
           }
       }catch(err){
           console.warn(`${err}获取当前值`);
           return '';
       }
}

/**
 * 获取表单值
 */
 export const getValue=(vaule:any, path:any)=>{
    return FormPath.getIn(vaule, path);
}